#include "Acceptor.h"

Acceptor::Acceptor(const string &ip, unsigned short port)
    : _addr(ip, port)
{
}

Acceptor::~Acceptor()
{
}

void Acceptor::ready()
{
    setReuseAddr();
    setReusePort();
    bind();
    listen();
}

int Acceptor::accept()
{
    int confd = ::accept(_sock.getFd(), nullptr, nullptr);
    if(-1 == confd)
    {
        perror("accept");
        return -1;
    }
    return confd;
}

int Acceptor::getFd()
{
    return _sock.getFd();
}

void Acceptor::setReuseAddr()
{
    int reuse = 1;
    int ret = ::setsockopt(_sock.getFd(), SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    if (ret)
    {
        perror("setsockopt");
    }
}

void Acceptor::setReusePort()
{
    int reuse = 1;
    int ret = ::setsockopt(_sock.getFd(), SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse));
    if (ret)
    {
        perror("setsockopt");
    }
}

void Acceptor::bind()
{
    int ret = ::bind(_sock.getFd(), (struct sockaddr *)_addr.getAddrPtr(), sizeof(struct sockaddr));
    if (-1 == ret)
    {
        perror("bind");
        return;
    }
}

void Acceptor::listen()
{
    int ret = ::listen(_sock.getFd(), 128);
    if (-1 == ret)
    {
        perror("listen");
        return;
    }
}
